//
//  HCScrollMenuBar.m
//  DFMarketModule
//
//  Created by Hotacool on 2017/9/28.
//  Copyright © 2017年 Hotacool Tea Party. All rights reserved.
//

#import "HCScrollMenuBar.h"
#import "HCUtilities.h"

static const CGFloat kScrollMenuBarFucButtonFont = 16;
static const CGFloat kScrollMenuBarItemTag = 100;
static const CGFloat kScrollMenuBarIndicatorAniDuration = 0.1;
static const CGFloat kScrollMenuBarIndicatorHeight = 2;
static const CGFloat kScrollMenuBarItemMinWidth = 60;
static const CGFloat kScrollMenuBarAddBtnWidth = 27;
static const CGFloat kScrollMenuBarMaskWidth = 50;
@interface HCScrollMenuBar () <UIScrollViewDelegate>
@property (nonatomic, strong, readwrite) UIScrollView *scrollView;
@property (nonatomic, strong, readwrite) UIButton *fucButton;
@property (nonatomic, strong, readwrite) UIButton *addButton;
@property (nonatomic, copy, readwrite) NSArray *itemArray;
@property (nonatomic, assign, readwrite) NSInteger selectIndex;
//滚动条
@property (nonatomic, strong) UIView *selectionIndicator;
//存放各按钮宽度数组
@property (nonatomic, strong) NSMutableArray * itemWidthArray;
@end

@implementation HCScrollMenuBar {
    NSMutableArray *_itemArray;
    UIImageView *mask;
}

- (instancetype)initWithItemArray:(NSArray *)itemArray {
    self = [super init];
    if (self) {
        _itemArray = [NSMutableArray arrayWithArray:itemArray];
        _buttonsArray = [[NSMutableArray alloc] init];
        _itemWidthArray = [[NSMutableArray alloc] init];
        _selectIndex = 0;
        _hasAddButton = _hasFucButton = NO;
        [self setUp];
    }
    return self;
}

- (void)setUp {
    _titleColorNormal = [UIColor blackColor];
    _titleColorSelect = [UIColor redColor];
    [self addSubview:self.scrollView];
    [self.scrollView addSubview:self.selectionIndicator];
    [self addSubview:self.fucButton];
    [self addItemButtonsToScrollView];
    
    mask = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"zixuanHeaderMask.png"]];
    mask.userInteractionEnabled = NO;
    [self addSubview:mask];
}

- (void)setHasAddButton:(BOOL)hasAddButton {
    _hasAddButton = hasAddButton;
    if (hasAddButton) {
        
    }
}

- (void)setIndicatorColor:(UIColor *)indicatorColor {
    _indicatorColor = indicatorColor;
    self.selectionIndicator.backgroundColor = indicatorColor;
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.backgroundColor = [UIColor clearColor];
        _scrollView.delegate = self;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.canCancelContentTouches = YES;
    }
    return _scrollView;
}

- (UIView *)selectionIndicator {
    if (!_selectionIndicator) {
        _selectionIndicator = [[UIView alloc] init];
        _selectionIndicator.backgroundColor = [UIColor redColor];
    }
    return _selectionIndicator;
}

- (UIButton *)fucButton {
    if (!_fucButton) {
        _fucButton = [[UIButton alloc] init];
        _fucButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_fucButton setImage:[HCUtilities imageWithName:@"zixuanEditBtn.png"] forState:UIControlStateNormal];
        //        _fucButton.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 10);
        [_fucButton addTarget:self action:@selector(fucButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    }
    return _fucButton;
}

- (UIButton *)addButton {
    if (!_addButton) {
        _addButton = [[UIButton alloc] init];
        [_addButton setImage:[UIImage imageNamed:@"zixuanGroupAdd.png"] forState:UIControlStateNormal];
        [_addButton addTarget:self action:@selector(addMoreColumnBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addButton;
}
#pragma mark 添加菜单按钮
-(void)addItemButtonsToScrollView {
    for (int i = 0; i < self.itemArray.count; i++) {
        UIButton *itemButton = [[UIButton alloc] init];
        [itemButton setBackgroundColor:[UIColor clearColor]];
        [itemButton setOpaque:YES];
        [itemButton setExclusiveTouch:YES];
        [itemButton setTag:i+kScrollMenuBarItemTag];
        [itemButton.titleLabel setFont:[UIFont systemFontOfSize:kScrollMenuBarFucButtonFont]];
        [itemButton setTitle:[self.itemArray objectAtIndex:i] forState:UIControlStateNormal];
        [itemButton setTitleColor:self.titleColorNormal forState:UIControlStateNormal];
        [itemButton setTitleColor:self.titleColorSelect forState:UIControlStateHighlighted];
        [itemButton setTitleColor:self.titleColorSelect forState:UIControlStateSelected];
        [itemButton addTarget:self action:@selector(didSelectItem:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.buttonsArray addObject:itemButton];
        [self.scrollView addSubview:itemButton];
    }
    //添加group btn
    [self.scrollView addSubview:self.addButton];
}

#pragma mark -
- (void)layoutSubviews {
    [super layoutSubviews];
    float selfWidth = CGRectGetWidth(self.bounds);
    float selfHeight = CGRectGetHeight(self.bounds);
//    float scrollViewLeftOrgX = 4.0f;
    
    float contentWidth = 0;
    [self.itemWidthArray removeAllObjects];
    
    for (int i = 0; i < self.itemArray.count; i++) {
        float width = _itemWidth;
        if (width <= 0) {
            UIFont *font = self.titleFontNormal?self.titleFontNormal:[UIFont systemFontOfSize:kScrollMenuBarFucButtonFont];
            width = [self.itemArray[i] boundingRectWithSize:CGSizeMake(MAXFLOAT, kScrollMenuBarItemMinWidth)
                                                          options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                                       attributes:@{NSFontAttributeName:font}
                                                          context:nil].size.width +10*2;
        }
        [self.itemWidthArray addObject:@(width)];
        contentWidth = width + contentWidth;
    }
    if (_hasAddButton) {
        //设置添加btn
        self.addButton.frame = CGRectMake(0, 0, kScrollMenuBarAddBtnWidth, kScrollMenuBarAddBtnWidth);
        contentWidth += self.addButton.frame.size.width+6;
    }
    if (_hasFucButton) {
        //设置更多按钮frame
        CGFloat funcWidth = self.funcWidth>0?self.funcWidth:kScrollMenuBarAddBtnWidth;
        CGFloat funHeight = funcWidth>selfHeight?selfHeight:funcWidth;
        [self.fucButton setFrame:CGRectMake(selfWidth-funcWidth, 0, funcWidth, funHeight)];
    }
    
    //设置滚动view的frame
    self.scrollView.frame = CGRectMake(_leftMargin, 0.0f, selfWidth - _leftMargin*2 - (_hasFucButton?CGRectGetWidth(self.fucButton.bounds):0), selfHeight);
    self.scrollView.contentSize = CGSizeMake(contentWidth, selfHeight);
    
    //判断Scrollview的contentWidth有没有超过frame的宽度，没有的话，要调整按钮的宽度
    float moreWidth = contentWidth - CGRectGetWidth(self.scrollView.bounds);
    
    if (moreWidth < 0) {
        mask.hidden = YES;
    } else {
        mask.hidden = NO;
        mask.frame = CGRectMake(selfWidth-self.fucButton.frame.size.width-kScrollMenuBarMaskWidth, 0, kScrollMenuBarMaskWidth, selfHeight);
    }
    
    //设置按钮frame
    float channelBtnOrgX = 0.0f;
    for (int i = 0; i < self.itemArray.count; i++) {
        float btnWidth = [self.itemWidthArray[i] floatValue];
        if(moreWidth<0&&_itemWidth<=0){//在外面不指定宽度的时候，才进行剩余宽度分配
            btnWidth = btnWidth - moreWidth/self.itemArray.count;
        }
        UIButton *button = (UIButton *)[self.scrollView viewWithTag:i + kScrollMenuBarItemTag];
        button.frame = CGRectMake(channelBtnOrgX, 1.0f, btnWidth, selfHeight-2);
        channelBtnOrgX = channelBtnOrgX + btnWidth;
        if (_itemWidth>0) {//如果等宽，则title大小自适应button宽度
            button.titleLabel.adjustsFontSizeToFitWidth = YES;
        }
    }
    if (_hasAddButton) {
        self.addButton.frame = CGRectMake(channelBtnOrgX, selfHeight/2-kScrollMenuBarAddBtnWidth/2, self.addButton.frame.size.width, self.addButton.frame.size.height);
    }
    
    [self setSelectIndex:self.selectIndex withAnimation:NO];
}

- (void)didSelectItem:(UIButton *)itemButton {
    NSInteger index = itemButton.tag - kScrollMenuBarItemTag;
    [self setSelectIndex:index withAnimation:YES];
    if ([self.delegate respondsToSelector:@selector(scrollMenuBar:selectAtIndex:)]) {
        [self.delegate scrollMenuBar:self selectAtIndex:self.selectIndex];
    }
}

- (void)addMoreColumnBtnClicked{
    if ([self.delegate respondsToSelector:@selector(clickAddButtonOfScrollMenuBar:)]) {
        [self.delegate clickAddButtonOfScrollMenuBar:self];
    }
}

- (void)fucButtonClicked {
    if ([self.delegate respondsToSelector:@selector(clickFucButtonOfScrollMenuBar:)]) {
        [self.delegate clickFucButtonOfScrollMenuBar:self];
    }
}

#pragma mark -- UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGPoint offset = scrollView.contentOffset;
    if (offset.x < scrollView.contentSize.width-scrollView.frame.size.width-5) {
        mask.hidden = NO;
    } else {
        mask.hidden = YES;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if ([self.delegate respondsToSelector:@selector(scrollMenuBarEndScroll:)]) {
        [self.delegate scrollMenuBarEndScroll:self];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if ([self.delegate respondsToSelector:@selector(scrollMenuBarEndScroll:)]) {
        [self.delegate scrollMenuBarEndScroll:self];
    }
}

#pragma mark -- api
- (void)setSelectIndex:(NSInteger)selectIndex withAnimation:(BOOL)animation {
    self.selectIndex = selectIndex;
    for (int i = 0; i < self.itemArray.count; i++) {
        UIButton *itemButton = (UIButton *)[self viewWithTag:i + kScrollMenuBarItemTag];
        itemButton.selected = NO;
        itemButton.backgroundColor = [UIColor clearColor];
    }
    UIButton *itemButton = (UIButton *)[self viewWithTag:selectIndex + kScrollMenuBarItemTag];
    itemButton.selected = YES;
    if (self.titleBackgroundColorSelect) {
        itemButton.backgroundColor = self.titleBackgroundColorSelect;
    }
    if (animation) {
        [UIView animateWithDuration:kScrollMenuBarIndicatorAniDuration
                         animations:^{
                             self.selectionIndicator.frame = CGRectMake(CGRectGetMinX(itemButton.frame), CGRectGetHeight(self.bounds) - kScrollMenuBarIndicatorHeight, CGRectGetWidth(itemButton.bounds), kScrollMenuBarIndicatorHeight);
                         }];
    }
    else {
        self.selectionIndicator.frame = CGRectMake(CGRectGetMinX(itemButton.frame), CGRectGetHeight(self.bounds) - kScrollMenuBarIndicatorHeight, CGRectGetWidth(itemButton.bounds), kScrollMenuBarIndicatorHeight);
    }
    //选中按钮居中
    CGFloat scrollViewWidth = CGRectGetWidth(self.scrollView.bounds);
    CGFloat scrollViewContentWidth = self.scrollView.contentSize.width;
    if(scrollViewContentWidth <= scrollViewWidth || scrollViewWidth <= 0){
        return;
    }
    CGFloat scrollViewOffSetX = itemButton.frame.origin.x + CGRectGetWidth(itemButton.bounds)/2 - scrollViewWidth/2;
    if(scrollViewOffSetX < 0.0f){
        scrollViewOffSetX = 0.0f;
    }
    if(scrollViewOffSetX + scrollViewWidth > scrollViewContentWidth){
        scrollViewOffSetX = scrollViewContentWidth - scrollViewWidth;
    }
    [self.scrollView setContentOffset:CGPointMake(scrollViewOffSetX, 0) animated:YES];
    // 优化按钮显示区域
    if (selectIndex > self.selectIndex) {
        if (CGRectGetMaxX(itemButton.frame) > CGRectGetWidth(self.scrollView.bounds) + self.scrollView.contentOffset.x) {
            [self.scrollView scrollRectToVisible:itemButton.frame animated:animation];
        }
    }
    else if (selectIndex < self.selectIndex){
        if (CGRectGetMinX(itemButton.frame) < self.scrollView.contentOffset.x) {
            [self.scrollView scrollRectToVisible:itemButton.frame animated:animation];
        }
    }
}

- (void)resetItemArray:(NSArray *)itemArray {
    for (UIButton *itemButton in self.buttonsArray) {
        [itemButton removeFromSuperview];
    }
    [self.buttonsArray removeAllObjects];
    [_itemArray removeAllObjects];
    [_itemArray addObjectsFromArray:itemArray];
    [self addItemButtonsToScrollView];
    [self setNeedsLayout];
}

#pragma mark - setter/getter
- (void)setTitleColorNormal:(UIColor *)titleColorNormal{
    _titleColorNormal = titleColorNormal;
    for (UIButton *button in self.buttonsArray) {
        [button setTitleColor:titleColorNormal forState:UIControlStateNormal];
    }
}

- (void)setTitleColorSelect:(UIColor *)titleColorSelect{
    _titleColorSelect = titleColorSelect;
    for (UIButton *button in self.buttonsArray) {
        [button setTitleColor:titleColorSelect forState:UIControlStateHighlighted];
        [button setTitleColor:titleColorSelect forState:UIControlStateSelected];
    }
}

- (void)setTitleFontNormal:(UIFont *)titleFontNormal{
    _titleFontNormal = titleFontNormal;
    for (UIButton *button in self.buttonsArray) {
        [button.titleLabel setFont:titleFontNormal];
    }
}


@end
